package com.cqcet.wenchuang.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cqcet.wenchuang.common.R;
import com.cqcet.wenchuang.entity.AddressBook;
import com.cqcet.wenchuang.service.AddressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 地址管理
 */
@Slf4j
@Api(tags = "地址管理接口")
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 新增地址
     * @param addressBook
     * @return
     */
    @ApiOperation(value = "新增地址", notes = "必要参数:userId,isDefault,address,phone,consignee")
    @PostMapping
    public R<String> save(@RequestBody AddressBook addressBook) {
        addressBookService.save(addressBook);
        return R.success("添加成功");
    }

    /**
     * 将已有的地址设置为默认地址
     * @param addressBookId
     * @return
     */
    @ApiOperation(value = "设为默认地址", notes = "必要参数:userId,id")
    @GetMapping("/saveAsDefault/{addressBookId}")
    public R<String> saveAsDefault(@PathVariable Long addressBookId) {
        addressBookService.saveAsDefault(addressBookId);
        return R.success("修改成功");
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @ApiOperation(value = "删除地址",notes = "必要参数:id")
    @DeleteMapping("/{id}")
    public R<String> remove(@PathVariable Long id) {
        addressBookService.removeById(id);
        return R.success("删除成功");
    }

    /**
     * 修改
     * @param addressBook
     * @return
     */
    @ApiOperation(value = "修改地址",notes = "必要参数:id,userId,isDefault,address,phone,consignee")
    @PutMapping
    public R<String> update(@RequestBody AddressBook addressBook) {
        addressBookService.updateById(addressBook);
        return R.success("修改成功");
    }

    /**
     * 获取默认地址
     * @param userId
     * @return
     */
    @ApiOperation(value = "获取默认地址",notes = "必要参数:id")
    @GetMapping("/getDefault/{userId}")
    public R<AddressBook> getDefaultAddress(@PathVariable Long userId) {
        return R.success(addressBookService.getDefaultAddress(userId));
    }

    /**
     * 获取用户全部地址
     * @param userId
     * @return
     */
    @ApiOperation(value = "获取用户所有地址", notes = "必要参数:userId")
    @GetMapping("/{userId}")
    public R<List<AddressBook>> list(@PathVariable Long userId) {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件
        queryWrapper.eq(AddressBook::getUserId, userId);
        //根据更新时间，添加时间降序排序
        queryWrapper.orderByDesc(AddressBook::getUpdateTime).orderByDesc(AddressBook::getCreateTime);

        List<AddressBook> addressBookList = addressBookService.list(queryWrapper);

        return R.success(addressBookList);
    }

}
